<template>
	<el-dialog v-model="dialogVisible" :title="`${title}菜品分类`" width="60%" center @close="dialogClose">
		<el-scrollbar height="600px">
			<el-form :model="form" label-width="120px">
				<el-form-item label="菜品名称">
					<el-input v-model="form.name" placeholder="请输入" />
				</el-form-item>

				<el-form-item label="菜品分类">
					<el-select v-model="form.categoryId" placeholder="请选择" style="width: 100%">
						<el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>

				<el-form-item label="菜品售价">
					<el-input-number v-model="form.price" :min="1" controls-position="right"
						style="width: 100%; text-align: left" />
				</el-form-item>

				<el-form-item label="售卖状态">
					<el-select v-model="form.status" placeholder="请选择" style="width: 100%">
						<el-option label="停售" :value="0" />
						<el-option label="起售" :value="1" />
					</el-select>
				</el-form-item>

				<el-form-item label="口味配置">
					<el-row style="width: 100%">
						<el-col :span="24" style="display: flex; margin-bottom: 10px" v-for="(item, index) in form.flavors"
							:key="index">
							<el-autocomplete v-model="item.name" :fetch-suggestions="querySearch" clearable placeholder="请选择"
								@select="handleSelect($event, item)" @change="handleChange(item)"
								style="width: 20%; margin-right: 10px" />

							<div style="border: 1px solid #dcdfe6; border-radius: 3px; width: 80%; padding: 0px 10px">
								<el-tag v-for="tag in item.value" :key="tag" class="mx-1" closable :disable-transitions="false"
									@close="handleClose(tag, item)" style="margin: 0px 5px">
									{{ tag }}
								</el-tag>
							</div>

							<el-button text style="color: red" @click="form.flavors.splice(index, 1)">删除</el-button>
						</el-col>

						<el-col :span="24">
							<el-button type="primary" color="#ffc200"
								@click="form.flavors.push({ name: '', value: [] })">添加口味</el-button>
						</el-col>
					</el-row>
				</el-form-item>

				<el-form-item label="图片">
					<el-upload v-if="!url" v-model:file-list="fileList" action="api/common/upload" list-type="picture-card"
						:on-success="handleSuccess" :show-file-list="false" :limit="1">
						<el-icon>
							<Plus />
						</el-icon>
					</el-upload>

					<el-image v-else style="width: 148px; height: 148px" :src="url" :zoom-rate="1.2" :preview-src-list="srcList"
						fit="cover" />
				</el-form-item>

				<el-form-item label="描述">
					<el-input v-model="form.description" :autosize="{ minRows: 3, maxRows: 9 }" type="textarea"
						placeholder="请输入" />
				</el-form-item>
			</el-form>
		</el-scrollbar>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogClose">取消</el-button>
				<el-button color="#ffc200" @click="addDishes"> 确认 </el-button>
				<el-button color="#383339"> 保存并继续添加菜品 </el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup name="DishesDialog">
import { reactive, toRefs, defineProps, defineEmits, ref, onMounted, getCurrentInstance } from 'vue'
import { DialogType } from '../types'
import type { UploadUserFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { downloadImg, getDishInfo, updateDish } from '@/api/index'
import { useRouter } from 'vue-router'
import { getCategoryList, saveDish } from '@/api/index'
import { ICategoryList, IFormType, IFlavorList } from '../types'

const router = useRouter()

const { proxy } = getCurrentInstance() as any

const form: IFormType = reactive({
	name: '',
	image: '',
	categoryId: '',
	price: null,
	status: null,
	flavors: [],
	description: ''
})

const fileList = ref<UploadUserFile[]>([])

// 接收父组件传参
const props = defineProps<{
	dialogParam: DialogType
}>()

const { dialogVisible, title } = toRefs(props.dialogParam)

const emit = defineEmits(['dialogClose'])
const dialogClose = () => {
	emit('dialogClose')
}

const url = ref() // 图片url
const srcList = ref<string[]>([]) // 预览图片数组

const handleSuccess = async (response: { data: string; code: number; msg: string }) => {
	// 判断用户是否登录
	response.code === 0 ? (response.msg === 'NOTLOGIN' ? router.push('/login') : true) : true

	downImg(response.data)
	form.image = response.data
}

/**
 * 下载图片
 * @param data 图片名称
 */
const downImg = async (data: string) => {
	try {
		// 获取图片地址
		const res = await downloadImg<Blob>({ name: data })
		// 使用 window.URL.createObjectURL 将图片流转为地址
		const path = window.URL.createObjectURL(new Blob([res as any], { type: 'image/png' }))
		url.value = path
		srcList.value.push(path)
	} catch (error) {
		console.log('%c [ error ]-155-「DishesDialog」', 'font-size:13px; background:#d64fcb; color:#ff93ff;', error)
		proxy.$message.error('图片下载失败')
	}

}

interface RestaurantItem {
	value: string
	arr: string[]
}

const createFilter = (queryString: string) => {
	return (restaurant: RestaurantItem) => {
		return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
	}
}

const restaurants = ref<RestaurantItem[]>([
	{ value: '甜味', arr: ['无糖', '少糖', '半糖', '多糖', '全糖'] },
	{ value: '温度', arr: ['热饮', '常温', '去冰', '少冰', '多冰'] },
	{ value: '忌口', arr: ['不要葱', '不要蒜', '不要香菜', '不要辣'] },
	{ value: '辣度', arr: ['不辣', '微辣', '中辣', '重辣'] }
])

const querySearch = (queryString: string, cb: any) => {
	const results = queryString ? restaurants.value.filter(createFilter(queryString)) : restaurants.value
	cb(results)
}

const handleSelect = (target: RestaurantItem, item: IFlavorList) => {
	item.value = JSON.parse(JSON.stringify(target.arr))
}

const handleChange = (item: IFlavorList) => {
	item.value = []
}

const handleClose = (tag: string, item: IFlavorList) => {
	item.value.splice(item.value.indexOf(tag), 1)
}

const addDishes = async () => {
	const params = JSON.parse(JSON.stringify({ ...form }))
	delete params.flavors
	params.flavors = form.flavors.map(item => ({ name: item.name, value: JSON.stringify(item.value) }))
	try {
		if (props.dialogParam.id) {
			const res = await updateDish(params)
			proxy.$message.success('修改成功')
			dialogClose()
		} else {
			const res = await saveDish<string>(params)
			proxy.$message.success('新增成功')
			dialogClose()
		}
	} catch (error) {
		proxy.$message.error(error)
	}
}

const categoryList = ref<ICategoryList[]>([])

const initData = async () => {
	try {
		// 获取菜品分类下拉数据
		const { data } = await getCategoryList<ICategoryList[]>({ type: 1 })
		categoryList.value = data

		if (props.dialogParam.title === '修改') {
			const res = await getDishInfo<IFormType>(props.dialogParam.id as string)
			const flavors = res.data.flavors.map(item => {
				item.value = JSON.parse(item.value as any)
				return item
			})
			downImg(res.data.image)
			form.name = res.data.name
			form.image = res.data.image
			form.categoryId = res.data.categoryId
			form.price = res.data.price
			form.status = res.data.status
			form.flavors = flavors
			form.description = res.data.description
			form.id = res.data.id
		}
	} catch (error) {
		proxy.$message.error(error)
	}
}

onMounted(() => {
	initData()
})
</script>

<style scoped lang="scss">
::v-deep .el-input-number .el-input__inner {
	text-align: left;
}

::v-deep .el-input-number__decrease,
::v-deep .el-input-number__increase {
	display: none;
}

.dialog-footer button:first-child {
	margin-right: 10px;
}
</style>
